Welcome to Django!

2.7 创建一个app

上节的临时方案,已经可以让项目结构清晰许多,但并不是最终的方案,针对这种问题,Django有相应的解决方案

Django的原则是一个项目中有多个app,每个app处理一个类型的服务,这样做的好处是职责分明,便于项目的维护和扩展。

具体做法:

第一步,使用startapp命令创建一个app

注意:创建的文件必须与url(引用文件)是同级,不然会报错。

python manage.py startapp hello

或者:

django-admin startapp hello

命令执行后,会有项目文件夹中新产生一个名字为hello(也是一个包)

Hello/

_init_.py          #空文件,标识hello是一个包

admin.py        #admin后台相关的文件

apps.py          #hello作为一个app可以配置的文件

migrations/    #记录数据库变更记录。

在hello文件夹下的views.py里面迁移代码


import os

from django.conf import settings

from django.shortcuts import HttpResponse,redirect,render


def hello(request):

filepath=os.path.join(settings.BASE_DIR, "shn" , "hello_world.html" )

with open (filepath, "r" ) as f:

content=f.read()

return HttpResponse(content,content_type= "text/html" , status = 200 )


def hello123(request):

return redirect( "https://www.baidu.com" )


第二步 在原url写上from hello import views as hello_views,会有点报错标红,但不影响使用,原因待查。

from django.urls import path,re_path      #需要导入re_path库

from django.contrib import admin

from .views import *      #将views导入

from hello import views as hello_views

from ariticles import views as ariticles_views


urlpatterns = [

path( 'admin/' , admin.site.urls),

path( 'hello' , hello_views.hello),

re_path(r "^ariticles/([0-9]{4})$" , ariticles_views.year_archive) , #无名分组

re_path(r "^ariticles/(?P < year > [0-9]{4})/(?P <month >[0-9]{2})$" , ariticles_views.month_archive),

# 有名分组,P必须是大写的,不然会报错

]